<!--
1、物品表格中的数量是实发数量
2、单价，金额有该列，但不可填
3、表单数据一页五个
4、表单选择为单选
 * @Author: your name
 * @Date: 2020-11-27 14:37:56
 * @LastEditTime: 2021-07-28 16:06:44
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cang-chu-guan-li-xi-tong\src\components\common\productPickingInfo.vue
-->

<template>
  <div>
    <!-- 原单生成按钮和表格 -->
    <a-button type="primary" style="margin-top: 20px" @click="showModal">
      <a-icon type="plus" />
      根据源单生成
    </a-button>
    <a-modal
      title="生产领料单生成生产材料出库单"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <!-- 公共部分 -->
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-item label="时间段">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-item label="申请部门">
              <a-tree-select
                v-model="searchForm.applicationDept"
                style="width: 100%"
                :tree-data="departmentList"
                @change="changeTreeNode"
                allow-clear
                show-search
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select
                v-model="searchForm.documentClosed"
                style="width: 100%"
                @change="setDocumentClosed"
              >
                <a-select-option
                  v-for="item in documentClosedList"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="单据编号">
              <a-select
                v-model="searchForm.document"
                style="width: 100%"
                showSearch
              >
                <a-select-option
                  v-for="(item, index) in SourceOrderList"
                  :key="index"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <!-- 按钮 -->
          <a-col
            :xl="24"
            :lg="24"
            :md="24"
            :sm="24"
            :xs="24"
            :style="{ textAlign: 'right' }"
            ><div style="margin-top: 10px">
              <a-button type="primary" @click="getsearch1()">查询</a-button>
              <a-button style="margin-left: 8px" @click="Reset()"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form>

      <a-divider />

      <!-- 生产领料单据 -->
      <a-table
        style="margin-top: 20px"
        :columns="orderColumns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderOnSelectChange,
          type: 'radio',
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <template slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="updateDocumentClosed(record)"
          >
            <a>开启</a>
          </a-popconfirm>
          <a-popconfirm
            v-if="record.documentClosed == '关闭'"
            title="是否开启单据?"
            @confirm="updateDocumentClosed(record)"
          >
            <a>关闭</a>
          </a-popconfirm>
        </template>
      </a-table>

      <a-divider />
      <!-- 单据中的物品 -->
      <a-table
        style="margin-top: 10px"
        :columns="listColumns"
        :data-source="listDataSource"
        :pagination="false"
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listOnSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <template slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            v-if="record.documentClosed == '开启'"
            title="是否关闭记录?"
            @confirm="updateDocumentRecordClosed(record)"
          >
            记录关闭
          </a-popconfirm>
          <a-popconfirm
            v-if="record.documentClosed == '关闭'"
            title="是否开启记录?"
            @confirm="updateDocumentRecordClosed(record)"
          >
            记录开启
          </a-popconfirm>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

import { ShenChanLingLiaoHTTP } from "@/services/modules/ChuKuGuanLi/ShengChanCaiLiaoChuKu/ShengChanLingLiao";
const $http = new ShenChanLingLiaoHTTP();

// import moment from "moment";
// 生产领料表单
const orderColumns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  {
    title: "申请单号",
    dataIndex: "requisitionNo",
    key: "requisitionNo",
    align: "center",
  },

  {
    title: "申请部门",
    dataIndex: "applicationDept_dictText",
    key: "applicationDept_dictText",
    align: "center",
  },
  {
    title: "申请日期",
    dataIndex: "applicationDate",
    key: "applicationDate",
    align: "center",
  },
  {
    title: "产成品仓库",
    dataIndex: "finishedProductDepot_dictText",
    key: "finishedProductDepot_dictText",
    align: "center",
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    key: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
  // {
  //   title: "供应商",
  //   dataIndex: "client_dictText",
  //   key: "client_dictText",
  //   align: "center",
  // },
];

// 生产领料物品列表
const listColumns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },

  {
    title: "仓库名称",
    dataIndex: "depotId_dictText",
    key: "depotId_dictText",
    align: "center",
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    scopedSlots: { customRender: "Number" },
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },

  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },
  {
    title: "数量",
    dataIndex: "actualQuantity",
    key: "actualQuantity",
    align: "center",
  },
  {
    title: "单价",
    dataIndex: "price",
    key: "price",
    align: "center",
  },
  {
    title: "金额",
    dataIndex: "cost",
    key: "cost",
    align: "center",
  },

  {
    title: "备注",
    key: "remark",
    dataIndex: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "记录关闭",
    dataIndex: "documentClosed",
    key: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];
export default {
  data() {
    return {
      documentClosedList: ["开启", "关闭"],
      sourceNumber: "", //源单号
      visible: false,
      pagination: {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        // pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
        pageSizeOptions: ["5", "10", "20"], //每页中显示的数据
      },

      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
      },

      searchForm: {
        document: "",
        rangeDate: null, // 时间范围
        // 部门
        applicationDept: "", // 部门名称
        departmentNo: "", // 部门编号
        documentClosed: "开启", //单据状态
      },
      orderColumns, // 表单列
      listColumns, // 列表列
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      // 订单左侧选择框
      orderSelectedRowKeys: [], // 订单选择
      dataSource: [],

      // 列表左侧选择框
      listSelectedRowKeys: [], // 列表选择
      listDataSource: [],

      startTime: "", // 开始时间
      endTime: "", // 结束时间

      // 备货通知单独有！！！！！
      departmentList: [], // 部门列表
      ApplyPersonList: [], // 出库申请人列表
      Form: {},
      selectedRowsId: "",
      SourceOrderList: [], //源单单号列表
    };
  },
  mounted() {
    this.getDeparmentTree(); //获取部门树
    this.getProducePickingInfo(); //获取生产领料单内容
    this.getSourceOrderList(); //获取生getSourceOrderList产领料单列表
  },
  methods: {
    setDocumentClosed(value) {
      console.log("value", value);
    },
    // 更新单据的状态函数
    updateDocumentClosed(record) {
      console.log("danjuzhuangtai", record);
      if (record.documentClosed == "开启") {
        let data = {
          documentClosed: "关闭",
          id: record.id,
        };
        console.log("data====》", data);

        $http.updateShengChanLingLiao(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("单据关闭成功！");
            this.getProducePickingInfo(); //获取生产领料单内容
          } else {
            this.$message.error("单据关闭失败！");
          }
        });
      } else {
        let data = {
          documentClosed: "开启",
          id: record.id,
        };
        console.log("data====》", data);

        $http.updateShengChanLingLiao(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("单据开启成功！");
            this.getProducePickingInfo(); //获取生产领料单内容
          } else {
            this.$message.error("单据开启失败！");
          }
        });
      }
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.documentClosed === "关闭",
        },
      };
    },
    // 更新物品的状态函数
    updateDocumentRecordClosed(record) {
      console.log("物品状态", record);
      if (record.documentClosed == "开启") {
        let data = {
          documentClosed: "关闭",
          id: record.id,
        };
        console.log("data====》", data);

        $http.updateShengChanLingLiaoRecord(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("记录关闭成功！");
            this.getProducePickingGoodsInfo(this.selectedRowsId);
          } else {
            this.$message.error("记录关闭失败！");
          }
        });
      } else {
        let data = {
          documentClosed: "开启",
          id: record.id,
        };
        console.log("data====》", data);

        $http.updateShengChanLingLiaoRecord(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("记录开启成功！");
            this.getProducePickingGoodsInfo(this.selectedRowsId);
          } else {
            this.$message.error("记录开启失败！");
          }
        });
      }
    },
    // 获取源单号列表
    getSourceOrderList() {
      let queryPath = "?string=SCSQ-";
      comHttp.getSourceNumber(queryPath).then((res) => {
        console.log("获取生产领料单源单列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          this.SourceOrderList.push(res.result[i]);
        }
      });
    },
    // 获取生产领料单的内容
    getProducePickingInfo(
      queryPath = "?pageNo=1&pageSize=5&status=审核通过&documentClosed=开启"
    ) {
      $http.getProducePickingInfo(queryPath).then((res) => {
        console.log("生产材料出库单", res);
        this.dataSource = [];
        const pagination = { ...this.pagination };
        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        this.pagination = pagination;

        this.dataSource = res.result.records;
        for (let i = 0; i < this.dataSource.length; i++) {
          this.dataSource[i].key = (res.result.current - 1) * 5 + i + 1;
        }
      });
    },
    /*     getProducePickingInfo(
      queryPath = "?pageNo=1&pageSize=5&status=审核通过&documentClosed=开启"
    ) {
      
      this.listSelectedRowKeys = [];
      this.listDataSource = [];
      this.orderSelectedRowKeys = [];
      // let pageNo = 1; //获取页码
      $http.getProducePickingInfo(queryPath).then((res) => {
        const pagination = { ...this.pagination };
        pagination.total = res.total;
        // pagination.pageSize = res.size;
        this.pagination = pagination;
        this.dataSource = [];

        console.log("获取生产领料单的内容", res);
        // this.render(res.result);
      });
    },
 */
    // 处理函数
    /* render(tempData) {
      // 设置分页
      const pagination = { ...this.pagination };
      pagination.total = tempData.total;

      this.pagination = pagination;

      let currentNum = tempData.current - 1;
      let dataSourceArr = [];
      for (let i = 0; i < tempData.records.length; i++) {
        let data = {
          key: currentNum * 5 + i + 1, //序号
          id: tempData.records[i].id, //主键id
          number: tempData.records[i].requisitionNo, //申请单号
          applicationDept: tempData.records[i].applicationDept, //申请部门
          applicationSector: tempData.records[i].applicationDept_dictText, //申请部门
          applicationDate: moment(tempData.records[i].applicationDate).format(
            "YYYY-MM-DD"
          ), //申请日期
          finishedProductDepot: tempData.records[i].finishedProductDepot, //产成品仓库Id
          finishedProductDepot_dictText:
            tempData.records[i].finishedProductDepot_dictText, //产成品仓库
          farmers_dictText: tempData.records[i].farmers_dictText, //供应商
          farmers: tempData.records[i].farmers, //供应商Id
          applicant: tempData.records[i].applicant, //申请人Id
          applicant_dictText: tempData.records[i].applicant_dictText, //申请人

          finishedProductType: tempData.records[i].finishedProductType, //产成品分类
          finishedProductType_dictText:
            tempData.records[i].finishedProductType_dictText, //产成品分类
          ownedBranch: tempData.records[i].ownedBranch, //所属分厂
          ownedBranch_dictText: tempData.records[i].ownedBranch_dictText, //所属分厂
          documentClosed: tempData.records[i].documentClosed, //单据状态
        };
        dataSourceArr.push(data);
      }
      this.dataSource = dataSourceArr;
    }, */

    // 2. 获取查询条件 函数,该函数会返回当前的查询条件， 搜索栏查询条件 + 分页的页码
    getQueryPath() {
      if (this.searchForm.applicationDeptId == undefined) {
        this.searchForm.applicationDeptId = "";
      }
      let queryPath =
        "?pageNo=" +
        this.queryParam.page +
        "&pageSize=" +
        this.queryParam.size +
        // "&startTime=" +
        "&beginDate=" +
        this.startTime +
        // "&endTime=" +
        "&endDate=" +
        this.endTime +
        "&deptId=" +
        this.searchForm.applicationDeptId +
        "&documentClosed=" +
        this.searchForm.documentClosed +
        "&document=" +
        this.searchForm.document;
      return queryPath; // 返回的查询条件
    },
    // 3. 重置当前页码及页码参数
    resetPagination() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        // pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      //查询参数
      this.queryParam = {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
      };
    },
    // 4、查询按钮触发函数——单独写，目的是在页码不为1时，点击查询，页码自动归1
    getsearch1() {
      this.resetPagination(); //重置页码和参数
      let queryPath = this.getQueryPath();
      console.log("当前的查询路径为:::", queryPath);
      this.getProducePickingInfo(queryPath);
      // this.resetPagination(); // 查询完后 需要重置页码和参数
    },
    // 5. 供分页调用的查询函数
    Search() {
      // 获取目前选择好的查询条件
      let queryPath = this.getQueryPath();
      // console.log("当前的查询路径为:::",queryPath);
      this.getProducePickingInfo(queryPath);
      //this.resetPagination(); // 查询完后 需要重置页码和参数
    },
    // ======================生产领料单选择=============================
    // 表格选择事件,
    orderOnSelectChange(selectedRowKeys, selectedRows) {
      this.orderSelectedRowKeys = selectedRowKeys;
      this.sourceNumber = selectedRows[0].number;
      this.selectedRowsId = selectedRows[0].id;
      this.getProducePickingGoodsInfo(selectedRows[0].id);
      this.listSelectedRowKeys = []; // 重置下面的选择按钮
      this.originData = [];
      this.Form = selectedRows[0]; // 把选中的行 放到 Form 中去
      console.log(this.Form, 33333333333);
    },
    // 通过生产领料单的单id，查询物品信息
    getProducePickingGoodsInfo(id) {
      console.log("id", id);
      $http.getProducePickingGoodsInfo("?headId=" + id).then((res) => {
        console.log("生产领料单的单号，查询物品信息", res);
        this.listDataSource = res.result.list;
        this.Form.goodsList = res.result.list;
        for (let i = 0; i < this.Form.goodsList.length; i++) {
          this.Form.goodsList[i].key = i + 1;
        }
        // this.render2(res.result);

      });
    },
    // 物品信息的处理函数
    // render2(tempData) {
    //   let dataSourceArr = [];
    //   for (let i = 0; i < tempData.list.length; i++) {
    //     let data = {
    //       key: i + 1, //序号
    //       id: tempData.list[i].id, //主键id
    //       affiliation: tempData.list[i].storageUnit_dictText, //所属单位
    //       affiliationId: tempData.list[i].storageUnit, //所属单位Id
    //       depotId: tempData.list[i].depotId, //仓库Id
    //       depotNo: tempData.list[i].depotIdBac_dictText, //仓库编码
    //       warehouse: tempData.list[i].depotId_dictText, //仓库名称
    //       inventoryId: tempData.list[i].inventoryId, //存货Id
    //       Number: tempData.list[i].inventoryNo, //存货编码
    //       goodName: tempData.list[i].invname, //存货名称
    //       standard: tempData.list[i].invspec, //规格型号
    //       unit: tempData.list[i].measname, //单位
    //       number2: tempData.list[i].actualQuantity, //数量
    //       price: tempData.list[i].price, //单价
    //       cost: tempData.list[i].money, //金额
    //       finishGoodsType: tempData.list[i].finishedProductType, //产成品分类Id
    //       finishedProductType_dictText:
    //         tempData.list[i].finishedProductType_dictText, //产成品分类
    //       remark: tempData.list[i].remark, //备注
    //       documentClosed: tempData.list[i].documentClosed, //单据状态
    //     };
    //     dataSourceArr.push(data);
    //   }
    //   this.listDataSource = dataSourceArr;
    // },

    // =============物品列表选择
    // 列表选择事件
    listOnSelectChange(selectedRowKeys, selectedRows) {
      this.originData = [];
      console.log(selectedRowKeys, 11111111111111111);
      console.log(selectedRows, 222222222222);
      this.listSelectedRowKeys = selectedRowKeys;
      this.Form.goodsList = selectedRows;

      // for (let i = 0; i < selectedRows.length; i++) {
      //   this.originData.push(selectedRows[i]);
      //   this.originData[i].sourceNumber = this.sourceNumber;
      // }
      // this.Form.goodsList = this.originData;

      // this.originData.push(this.sourceNumber);
      // console.log("originData", this.originData);
      // this.getProducePickingGoodsInfo(selectedRowKeys.id);
    },

    // 分页函数
    handleTableChange(pagination) {
      console.log("pagination===========>", pagination);
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      this.Search();
    },
    // ---------- 公用函数 ----------

    // 重置
    Reset() {
      this.searchForm = {
        documentClosed: "开启",
        document: "",
      };
      this.startTime = "";
      this.endTime = "";
      this.getProducePickingInfo();

      this.resetPagination(); // 重置分页情况

      this.listDataSource = []; // 重置物品数据
      // 重置选择框中选中的值
      this.listSelectedRowKeys = [];
      this.orderSelectedRowKeys = [];
    },
    // 展示对话框
    showModal() {
      this.getProducePickingInfo(); //获取生产领料单内容
      this.visible = true;
      console.log("this.visible", this.visible);
    },
    // 提交
    handleOk() {
      console.log("下方物品数据:::", this.Form);
      if (this.Form.goodsList) {
        this.$emit("origin-data", this.Form); //将子组件的数据，传递到父组件
        this.visible = false;
      } else {
        this.$message.error("请选择物品信息");
      }
      this.Reset();
    },
    // 清空
    Empty() {
      this.listDataSource = [];
      console.log("清空");
    },
    // 取消
    handleCancel() {
      this.visible = false;
    },
    // ===============搜索部分完成=================
    // 时间段
    getRangeTime(date, dateString) {
      this.startTime = dateString[0];
      this.endTime = dateString[1];
      console.log(this.startTime);
      console.log(this.endTime);
    },
    // 获取部门列表
    getDeparmentTree() {
      comHttp.getDepartmentList().then((res) => {
        // let tree = this.resetTree(res.result);
        console.log("获取部门树::::", res.result);
        this.departmentList = res.result;
        console.log(this.departmentList, "11111111");
        // this.resetTree(this.departmentList);
        this.changeCorpData(this.departmentList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.pkDeptdoc;
        element["value"] = element.deptname;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    // 部门下拉框选择
    changeTreeNode(value, key, c) {
      console.log("key", key);
      console.log("value", value);
      console.log("c", c);
      this.searchForm.applicationDeptId = c.triggerNode.eventKey;
      this.searchForm.applicationDept = key;
      console.log("选择的值::::", this.searchForm.applicationDept);
      console.log("applicationDeptId::::", this.searchForm.applicationDeptId);
    },
    // 树节点的 value值 变成 title,为了加上搜索框.
    // resetTree(Tree) {
    //   Tree.forEach((item) => {
    //     item.value = item.title;
    //     if (item.children) {
    //       this.resetTree(item.children);
    //     }
    //   });
    // },
    // 部门下拉框选择
    // changeTreeNode(value, label, extra) {
    //   this.searchForm.departmentNo = extra.triggerNode.eventKey;
    //   console.log("选择的值::::", this.searchForm.departmentNo);
    // },
  },
};
</script>

<style></style>
